<template>
    <div class="ml-16px mr-16px mb-16px pt-26px content-container">
        <div class="pl-26px pr-26px words-container">
            <div class="flex items-center pl-36px pt-26px -mt-26px -ml-26px text-14px font-bold level-2-title">
                自定义组合
            </div>
            <el-row :gutter="26" class="mt-16px">
                <el-col :span="12">
                    <Area :rule-form="ruleForm" />
                </el-col>
                <el-col :span="12">
                    <FrontKeyword :rule-form="ruleForm" />
                </el-col>
            </el-row>
            <el-row :gutter="26" class="mt-26px">
                <el-col :span="12">
                    <MainKeyword :rule-form="ruleForm" />
                </el-col>
                <el-col :span="12">
                    <BackKeyword :rule-form="ruleForm" />
                </el-col>
            </el-row>
        </div>
        <Combination :rule-form="ruleForm" v-if="ruleForm.combinations.length" />
        <CustomizeKeyword :rule-form="ruleForm" />
        <div class="pl-26px pb-40px">
            <el-button :loading="loading" type="primary" @click="handleNext">确认提交</el-button>
        </div>
        <ConfirmWord v-model:isConfirmDialogVisible="isConfirmDialogVisible" :rule-form="ruleForm"
            @closeDialog="handleClose" @confirm="handleConfirm" />
    </div>

</template>

<script setup lang="ts">
import CustomizeKeyword from './components/CustomizeKeyword.vue'
import Area from './components/Area.vue'
import FrontKeyword from './components/FrontKeyword.vue'
import MainKeyword from './components/MainKeyword.vue'
import BackKeyword from './components/BackKeyword.vue'
import ConfirmWord from './components/ConfirmWord.vue'
import Combination from './components/Combination.vue'
import { confirmMessageBox } from '@/utils/elMessageBox'
import { CircleCloseFilled, SuccessFilled } from '@element-plus/icons-vue'
import { getProjectKeywordApi, addProjectKeywordApi, combineWordsApi } from '@/api/geo'
import { useHead } from '@vueuse/head'
import { IFWord } from '@/api/geo/types'
import { useUserStore } from '@/store/modules/user'

const ruleForm = reactive({
    id: 0,
    area: '',
    city:'',
    frontWords: <IFWord[]>[],
    mainWords: [],
    backWords: [],
    cusKeyword: '',
    deleteWord:'',
    combination: 0,
    combinations: [],   //自定义组合
    combinationOptions: [],  //多选自定义组合集合
    combinationsFW: <string[]>[],  //前置预设集合
    combinationsBW: <string[]>[],   //后置预设集合
    fwCombinations: <{ label: string, words: string[] }[]>[],
    bwCombinations: <{ label: string, words: string[] }[]>[],
    FMBWords: <string[]>[],
})

const router = useRouter()

const userStore = useUserStore()

const isConfirmDialogVisible = ref(false)

const loading = ref(false)

async function handleNext() {
    try {
        const res = await combineWordsApi({
            zhukey: convertWord(ruleForm.mainWords),
            leftkeydata: ruleForm.frontWords,
            rightkeydata: ruleForm.backWords,
            Type: ruleForm.combinationOptions,
        })
        console.log(res)
        if (res.code === 200) {
            ruleForm.FMBWords = res.data    //有不有前缀和后缀都要弹窗
            loading.value = false
            isConfirmDialogVisible.value = true
        }
    } catch (error: any) {
        if (error.response && error.response.status === 405) {
            confirmMessageBox(CircleCloseFilled, error.response.data.message)
            loading.value = false
        }
    }
}

async function handleConfirm() {
    try {
        const res = await addProjectKeywordApi({
            ID: ruleForm.id,
            Region: ruleForm.area,
            Keyword: convertWord(ruleForm.mainWords),
            leftkeydata: ruleForm.frontWords,
            rightkeydata: ruleForm.backWords,
            CusKeyword: ruleForm.cusKeyword,
            DeleteKeyword:ruleForm.deleteWord.endsWith("/") ? ruleForm.deleteWord.slice(0, -1) : ruleForm.deleteWord,
            Type: ruleForm.combinationOptions
        })
        if (res.code === 200) {
            loading.value = false
            confirmMessageBox(SuccessFilled, res.message)
            router.push({
                path: '/geo/project-management/distillation-list'
            })
        }
    } catch (error: any) {
        if (error.response && error.response.status === 405) {
            confirmMessageBox(CircleCloseFilled, error.response.data.message)
            loading.value = false
        }
    }
}

async function getProjectKeyword() {
    try {
        const res: ResType = await getProjectKeywordApi()
        console.log(res)
        if (res.code === 200) {
            ruleForm.frontWords = res.leftkeydata
            ruleForm.backWords = res.rightkeydata
            ruleForm.mainWords = res.mainkeydata
            ruleForm.deleteWord = res.deletekeydata.join('/')
            ruleForm.cusKeyword = res.data.CusKeyword
            ruleForm.id = res.data.ID || 0
            ruleForm.combinations = res.gpresetlist
        }
    } catch (error: any) {
        if (error.response && error.response.status === 405) {
            confirmMessageBox(CircleCloseFilled, error.response.data.message,'','',() => {
                router.push({ 
                    path:'/geo/project-management/project-add'
                })
            })
        }
    }
}

//查找arr1的项是否是arr2的label,如果不是就将该项添加到arr2的首位去
function addMissingItemsToFrontOptimized(arr1: any, arr2: any) {
    // 创建 arr2 所有 label 的集合
    const labelSet = new Set(arr2.map((obj: any) => obj.label));
    // 创建 arr2 的副本
    const newArr2 = [...arr2];
    // 创建要添加的项（反向顺序）
    const itemsToAdd = [];
    let proxyCity: { label: string; value: number } = { label: '', value: 0 };
    // 遍历 arr1 找出缺失项
    for (const item of arr1) {
        if (!labelSet.has(item)) {
            proxyCity = new Proxy({ label: item, value: 1,customize:true }, {});
            itemsToAdd.unshift(proxyCity);
        }
    }
    // 将缺失项添加到数组开头
    newArr2.unshift(...itemsToAdd);
    return newArr2;
}

async function handleClose() {
    loading.value = false
    isConfirmDialogVisible.value = false
    //取消上一次删除关键词的操作
    const res: ResType = await getProjectKeywordApi()
    if (res.code === 200) {
        ruleForm.deleteWord = res.deletekeydata.join('/')
    }
}

function convertWord(obj: any) {
    if (obj.length) {
        const labels = obj
            .filter((item: any) => item.value === 1)
            .map((item: any) => item.label);
        return labels.join('/').replace(/\/$/, '');
    }else{
        return ''
    }
}

useHead({
    title: 'GEO：引擎之上，生成万象 - 兴旺宝',
})

onMounted(() => {
    getProjectKeyword()
})


</script>

<style scoped>
:deep(.el-checkbox-group) {
    display: flex;
    flex-direction: column;
}
</style>